package org.ligson.fwc.core.util;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.ListableBeanFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;


/**
 * 服务定位器，业务代码通常情况下可以通过spring注入的方式获得其他接口的实力，
 * 某些特殊情况下，无法自动注入时可以使用此类来获取其他服务实例
 *
 * @author KEN
 */
public class ServiceLocator {
    private static ListableBeanFactory beanFactory;

    public static <T> T getService(Class<T> type) {
        return beanFactory.getBean(type);
    }

    public static <T> T getService(String typeClazzName) {
        try {
            @SuppressWarnings("unchecked")
            T t = (T) getService(Class.forName(typeClazzName));
            return t;
        } catch (BeansException | ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    @Service
    @Lazy(false)
    private static class BeanFactoryHolder implements BeanFactoryAware {
        @Override
        public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
            ServiceLocator.beanFactory = (ListableBeanFactory) beanFactory;
        }
    }
}
